package demo.rxjava;

import java.util.Arrays;
import java.util.List;
import java.util.Random;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Func0;

/**
 * @author Arnold Yand
 * @since Mar 18, 2017 9:45:37 AM
 * @summary demo.rxjava.RxJavaDemo.java
 */
public class RxJavaDemo {

  public static void main(String[] args) {

    final Random rnd = new Random(System.currentTimeMillis());

    List<String> arr = Arrays.asList("2", "aaa", "iii");

    Observable<String> sender1 = Observable.create(new Observable.OnSubscribe<String>() {

      @Override
      public void call(Subscriber<? super String> sub) {
        sub.onNext("sender1 result:" + rnd.nextInt());
      }

    });

    Observable<String> sender2 = Observable.just("sender2 result:" + rnd.nextInt());

    Observable<String> sender3 = Observable.from(arr);

    Observable<String> sender4 = Observable.defer(new Func0<Observable<String>>() {
      /**
       * create Observable when Subscriber is existed
       */
      @Override
      public Observable<String> call() {
        return Observable.just("send4 result:" + rnd.nextInt());
      }
    });

    Observer<String> receiver = new Observer<String>() {

      @Override
      public void onCompleted() {
        System.out.println("completed!!!");
      }

      @Override
      public void onError(Throwable e) {
        e.printStackTrace();
      }

      @Override
      public void onNext(String t) {
        System.out.println("get " + t);
      }
    };

    sender1.subscribe(receiver);

  }

}
